// pages/my/index.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
const utils = require("../../utils/util");
const db = wx.cloud.database();
const app = getApp();
const openId = wx.getStorageSync('openId');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 微信版本是否支持
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    // 总数
    sumNum: 0,
    //待办数
    backlogNum: 0,
    //完成
    completeNum: 0,
    //用户信息
    nickname: '',//昵称
    avatarUrl: '',//头像
    sex: ''//性别
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取OpenId
    if (!openId) {
      getOpenId();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    // 获取完成时
    getSumNum(that);
    //获取待办数
    getBacklogNum(that);
    //获取完成数
    getCompleteNum(that);
    //获取用户信息
    getUser(that, openId);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // 设置分享标题
    return {
      title: app.globalData.shareTitle,
      path: '/pages/index/index'
    }
  },
  /**
   * 授权
   */
  onGetUserInfo: function ({ detail }) {
    var that = this;
    var openId = wx.getStorageSync('openId');
    if (detail.userInfo) {
      var userInfo = detail.userInfo;
      var sex = userInfo.gender == 1 ? '先生' : userInfo.gender == 2 ? '女士' : '未知';
      var nickname = userInfo.nickName;
      var avatarUrl = userInfo.avatarUrl;

      //添加用戶信息
      addUser(openId, sex, nickname, avatarUrl);

      that.setData({
        sex: sex,
        nickname: nickname,
        avatarUrl: avatarUrl
      })
      wx.setStorageSync('sex', sex);
      wx.setStorageSync('nickname', nickname);
      wx.setStorageSync('avatarUrl', avatarUrl);
    }
  },
  /**
   * 进入到备忘列表页
   */
  onMemoList: function () {
    //返回上一页
    wx.navigateBack({});
  },
  /**
   * 进入搜索备忘页面
   */
  onSearchMemo: function () {
    wx.navigateTo({
      url: '/pages/searchMemo/index',
    })
  },
  /**
   * 联系客服
   */
  onCustomerService: function () {
    wx.makePhoneCall({
      phoneNumber: '111-1111-1111' //仅为示例，并非真实的电话号码
    })
  },
  /**
   * 进入关于码友页面
   */
  onAbout: function () {
    wx.navigateTo({
      url: '/pages/about/index',
    })
  }
})


/**
 * 获取总数
 * @param {*} that 
 */
function getSumNum(that) {
  db.collection(app.globalData.memoCollection)
    .count()
    .then(res => {
      if (res.errMsg.indexOf('count:ok') != -1) {
        that.setData({
          sumNum: res.total
        })
      }
    })
    .catch(error => {
      Toast.loading({
        type: 'text',
        duration: 1500,
        message: error.errMsg
      });
    })
}


/**
 * 获取待办数
 * @param {*} that 
 */
function getBacklogNum(that) {
  db.collection(app.globalData.memoCollection)
    .where({
      status: 0
    })
    .count()
    .then(res => {
      if (res.errMsg.indexOf('count:ok') != -1) {
        that.setData({
          backlogNum: res.total
        })
      }
    })
    .catch(error => {
      Toast.loading({
        type: 'text',
        duration: 1500,
        message: error.errMsg
      });
    })
}

/**
 * 获取完成数
 * @param {*} that 
 */
function getCompleteNum(that) {
  db.collection(app.globalData.memoCollection)
    .where({
      status: 1
    })
    .count()
    .then(res => {
      if (res.errMsg.indexOf('count:ok') != -1) {
        that.setData({
          completeNum: res.total
        })
      }
    })
    .catch(error => {
      Toast.loading({
        type: 'text',
        duration: 1500,
        message: error.errMsg
      });
    })
}


/**
 * 获取用户信息
 * @param {*} that 
 */
function getUser(that, openId) {
  db.collection(app.globalData.userCollection)
    .where({
      _openid: openId
    })
    .get()
    .then(res => {
      if (res.errMsg.indexOf('get:ok') != -1) {
        var data = res.data[0];
        if (data) {
          var sex = data.sex;
          var nickname = data.nickname;
          var avatarUrl = data.avatar_url;
          that.setData({
            sex: sex,
            nickname: nickname,
            avatarUrl: avatarUrl
          })
          wx.setStorageSync('sex', sex);
          wx.setStorageSync('nickname', nickname);
          wx.setStorageSync('avatarUrl', avatarUrl);
        }
      }
    })
    .catch(error => {
      Toast.loading({
        type: 'text',
        duration: 1500,
        message: error.errMsg
      });
    })
}


/**
 * 添加用户信息
 */
function addUser(openId, sex, nickname, avatarUrl) {
  db.collection(app.globalData.userCollection)
    .where({
      _openid: openId
    })
    .get()
    .then(res => {
      var data = res.data;
      if (data.length) {
        db.collection(app.globalData.userCollection).doc(data[0]._id)
          .update({
            data: {
              sex: sex,
              nickname: nickname,
              avatar_url: avatarUrl,
              update_time: utils.formatTime(new Date())
            }
          })
          .then(res => {
            if (res && res.errMsg.indexOf('update:ok') != -1) {
              Toast('授权成功');
            }
          })
          .catch(error => {
            Toast.loading({
              type: 'text',
              duration: 1500,
              message: error.errMsg
            });
          })
      } else {
        db.collection(app.globalData.userCollection)
          .add({
            data: {
              sex: sex,
              nickname: nickname,
              avatar_url: avatarUrl,
              create_time: utils.formatTime(new Date()),
              update_time: utils.formatTime(new Date())
            }
          }).then(res => {
            if (res && res._id && res.errMsg.indexOf('add:ok') != -1) {
              Toast('授权成功');
            }
          })
          .catch(error => {
            Toast.loading({
              type: 'text',
              duration: 1500,
              message: error.errMsg
            });
          })
      }
    })
    .catch(error => {
      Toast.loading({
        type: 'text',
        duration: 1500,
        message: error.errMsg
      });
    })
}


/**
 * 获取OpenId
 */
function getOpenId() {
  // 调用云函数
  wx.cloud.callFunction({
    name: 'login',
    data: {},
    success: res => {
      var openId = res.result.openid;
      app.globalData.openid = openId;
      wx.setStorageSync('openId', openId);
    },
    fail: err => {
      console.error('[云函数] [login] 调用失败', err)
    }
  })
}